let userRequest = require("../../script/request/user.js");
/*********************************************
 * setUserInfo 设置用户信息 - IF WX AUTH = ON *
 *********************************************/
function setUserInfo(call){ 
  /**
   * wxGetUserInfoSuccess 获得用户信息回调
   */
  function wxGetUserInfoSuccess(res){
    let userInfo = res.userInfo;
    wx.setStorageSync('userInfo', userInfo);
    updateUserDetail(call);
  }
  /** 微信接口，获取用户信息 */
  wx.getUserInfo({ success: wxGetUserInfoSuccess })
}
module.exports.setUserInfo = setUserInfo;
/****************************
 * getUserInfo 获取用户信息 *
 ****************************/
function getUserInfo(){ return wx.getStorageSync('userInfo');}
module.exports.getUserInfo = getUserInfo;
/***************************** 
 * setUserDetail 设置用户详情 *
 *****************************/
function setUserDetail(userDetail) { wx.setStorageSync('userDetail', userDetail); }
/*****************************
 * getUserDetail 获取用户详情 *
 *****************************/
function getUserDetail() { return wx.getStorageSync('userDetail'); }
module.exports.getUserDetail = getUserDetail;
/***********************
 * getUserId 获取用户id *
 ***********************/
function getUserId() {
  return getUserDetail()['uid'];
}
module.exports.getUserId = getUserId;
/********************************
 * updateUserDetail 同步用户详情 *
 ********************************/
function updateUserDetail(call) {
  let userInfo = getUserInfo();
  let nickname = userInfo['nickName'];
  let avatar = userInfo['avatarUrl']; 
  userRequest.update({ nickname: nickname, avatar: avatar }, {
    success: function (r) {
      wx.setStorageSync('userDetail', r.data);
      (call||(()=>{}))();
    }
  });
}
module.exports.updateUserDetail = updateUserDetail;
/**************************
 * setSession 设置Session *
 **************************/
function setSession(call){
  function wxLoginSuccess(res) {
    let code = res.code;
    function getSessionsuccess(r) {
      let session = r.data
      wx.setStorageSync('tokenSession', r.data);
      call(session);
    }
    userRequest.getSession({ code: code }, { success: getSessionsuccess });
  }
  wx.login({ success: wxLoginSuccess });
}
/**************************
 * getSession 获取Session *
 **************************/
function getSession(){
  return wx.getStorageSync('tokenSession');
}
/*****************
 * login 用户登入*
 *****************/
function login(call){
  let openid;
  let session = getSession();
  function sendRequest(openid){
    let loginSccuess = function(res){
      setUserDetail(res.data);
      try{
        setUserInfo(function () {
          updateUserDetail();
        });
      } catch (e){ console.log("without wx auth...")}
     
      call();
    }
    userRequest.wxLogin({ open_id: openid }, { success: loginSccuess })
  }
  try {
    openid = session['openid'];
    if (openid == undefined) throw new Error;
    sendRequest(openid);
  } catch(e){
    setSession(function (session){
      openid = session['openid'];
      sendRequest(openid);
    })
  }
}
module.exports.login = login;

/******************
 * _init 注册函数 *
 ******************/
module.exports._init = function (that) {
  that._appendUserCard = _appendUserCard.bind(that);
  
  // console.log(getUserDetail());
  if (!getUserDetail()['img'] && !getUserDetail()['avatar']) {
    that._saveData("_USER_CHECK_STATUS_FALSE_", true);
    that._saveData("_USER_CHECK_BUTTON_STYLE_","top:-2rpx;position:fixed;z-index:999;"+
      "width:calc(100% + 4rpx);height:100%;padding:0;left: -2rpx;" +
      "background: linear-gradient(to bottom,rgba(0,0,0,0) 0%, rgba(0,0,0,0.3) 50% , rgba(0,0,0,0.5) 100%);"+
      "margin:0;border-radius:0;border:none;");
    that._USER_CHECK_CALLBACK_ = function (e) {
      if (e.detail.errMsg == "getUserInfo:ok") {
        setUserInfo(function(){
          that._saveData("_USER_CHECK_", '');
          function loginSuccess() {
            that._saveData("_USER_CHECK_STATUS_FALSE_", false);
            that.onLoad(that.options);
          }
          login(loginSuccess);
        });
      }
    }
  } else {
    that._saveData("_USCD_/_detail", getUserDetail());
    
    function loginSuccess() {
      getApp().logined = true;
      that._saveData("_USER_CHECK_STATUS_FALSE_", false);      
      that.onLoad(that.options);
    }
    if(!getApp().logined ){
      login(loginSuccess);
    }
  }
}

/**
 * _appendUserCard 添加名片支持
 */
function _appendUserCard(user) {
  let detail = user || getUserDetail();
  /** 判断是否是本人 */
  let isMine = user ? false : true;
  // isMine = false;
  this._saveData("_USCD_/isMine", isMine);
  if (isMine) {
    appendSignApply.bind(this)();
  } else {
    appendAimApply.bind(this)();
  }
  /**
   * appendAimApply 添加关注支持
   */
  function appendAimApply(){
    /** 加载关注功能判断 */
    let target_id = detail.uid;
    let from_id = getUserId();
    this._request('aim').checkAim({ target_id, from_id }, { success: getAimSuccess.bind(this) });
    function getAimSuccess(res) {
      this._saveData("_USCD_/aimClass", ['icon-toAim', 'icon-Aimed', 'icon-aimEach'][res.result]);
      this._saveData("_USCD_/aimText", ['关注', '已关注', '互相关注'][res.result]);
      
      this._USCD_AIM_TAP_ = function () {
        let handler = this._request('aim')[['fightAim', 'cancelAim'][res.result == 0 ? 0 : 1]];
        handler({ target_id, from_id }, { success: appendAimApply.bind(this) });
      }
    }
  }
  /**
   * appendSignApply 添加签名支持
   */
  function appendSignApply(){
    /** 修改签名功能 */
    this._USCD_EDIT_SIGN_ = function (e) {
      console.log(e);
      let sign = e.detail.value.sign;
      this._request('user').update({ sign }, { success: updateSuccess.bind(this) });
      function updateSuccess(r) {
        wx.setStorageSync('userDetail', r.data);
        this._saveData("_USCD_/detail", r.data);
        this._saveData("cache/showEditSignModal",0);   
      }
      
    }
  }

  this._saveData("_USCD_/detail", detail);
  this._saveData("_USCD_/icons", (function () {
    let icons = [];
    for (let i = 0; i < 9; i++) {
      let icon = {};

      icon.class = 'iconfont d-i-b-vat icon-food-' + (i + 1);
      icon.style = 'font-size: ' + ((1 * Math.random()) + 1) + 'rem; color: #f77d7d;';
      icon.style += 'padding-left: ' + (Math.round(3 * Math.random()) + 1) + 'rem;';
      icon.style += 'padding-top: ' + (Math.round(3 * Math.random()) + 1) + 'rem;';
      icon.style += 'margin-top: ' + (Math.round(3 * Math.random()) - 3) + 'rem;';

      icons.push(icon);
    }
    return icons;
  })());
  this._saveData("_USCD_/setting",(function(){
    let setting = [];
    setting.push({'class': 'icon-share-s'});
    return setting;
  })());
}